package org.oslims.client.uicomponents;

import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.cellview.client.Header;
import com.google.gwt.user.client.ui.AbstractImagePrototype;

/**
 * A {@link Header} subclass that maintains sorting state and displays an icon
 * to indicate the sort direction.
 */
public class SortableHeader extends Header<String> {

	/**
	 * Image resources.
	 */
	public static interface Resources extends ClientBundle {

		ImageResource downArrow();

		ImageResource upArrow();
	}

	private static final Resources RESOURCES = GWT.create(Resources.class);
	private static final int IMAGE_WIDTH = 16;
	private static final String DOWN_ARROW = makeImage(RESOURCES.downArrow());
	private static final String UP_ARROW = makeImage(RESOURCES.upArrow());

	private static String makeImage(ImageResource resource) {
		AbstractImagePrototype proto = AbstractImagePrototype.create(resource);
		return proto.getHTML().replace("style='", "style='position:absolute;right:0px;top:8px;");
	}

	private boolean reverseSort = false;
	private boolean sorted = false;
	private String text;
	private String propertyName;

	public SortableHeader(String text, String propertyName) {
		super(new ClickableTextCell());
		this.text = text;
		this.propertyName = propertyName;
	}

	public boolean getReverseSort() {
		return reverseSort;
	}

	@Override
	public String getValue() {
		return text;
	}

	@Override
	public void render(StringBuilder sb) {
		int imageWidth = IMAGE_WIDTH;
		sb.append("<div style='position:relative;cursor:hand;cursor:pointer;");
		sb.append("padding-right:");
		sb.append(imageWidth);
		sb.append("px;'>");
		if (sorted) {
			if (reverseSort) {
				sb.append(DOWN_ARROW);
			} else {
				sb.append(UP_ARROW);
			}
		} else {
			sb.append("<div style='position:absolute;display:none;'></div>");
		}
		sb.append("<div>");
		sb.append(text);
		sb.append("</div></div>");
	}

	public void setReverseSort(boolean reverseSort) {
		this.reverseSort = reverseSort;
	}

	public void setSorted(boolean sorted) {
		this.sorted = sorted;
	}

	public void toggleReverseSort() {
		this.reverseSort = !this.reverseSort;
	}

	public void setPropertyName(String propertyName) {
		this.propertyName = propertyName;
	}

	public String getPropertyName() {
		return propertyName;
	}
}
